<?php
declare (strict_types=1);

namespace app\common\model;

use app\common\tool\ApiClient;

class Area extends Base
{
    public static function getArea($parent_code = 100000, $level = 1)
    {
        switch ($level) {
            case 1:
                $filed = 'province as title';
                break;
            case 2:
                $filed = 'city as title';
                break;
            case 3:
                $filed = 'district as title';
                break;
            case 4:
                $filed = 'town as title';
                break;
        }

        return parent::where(['parent_code' => $parent_code, 'level' => $level])
            ->field('code,' . $filed)->select();
    }

    public static function mapLocation($province, $city, $district, $details): array
    {
        try {
            if ($district) {
                $area = parent::where(['code' => $district])->find();
                $address = $area['province'] . $area['city'] . $area['district'] . $details;
            } elseif ($city) {
                $area = parent::where(['code' => $city])->find();
                $address = $area['province'] . $area['city'] . $details;
            } elseif ($province) {
                $area = parent::where(['code' => $province])->find();
                $address = $area['province'] . $details;
            } else {
                $address = $details;
            }
            $config = config('map');
            $data['get'] = [
                'key' => $config['key'],
                'address' => $address
            ];
            $result = ApiClient::create($config['domain'])->get('', $data);
            if ($result->isSuccess()) {
                $result = $result->toArray();
                if ($result['status'] != 0) {
                    throw new \Exception($result['message']);
                }
                $data = $result['result']['location'];
            } else {
                throw new \Exception('请求失败');
            }

        } catch (\Exception $e) {

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        return ['code' => 1, 'msg' => 'success', 'data' => $data];
    }
}